package com.h2cloud.JUCTest.reentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

import static com.h2cloud.JUCTest.TimeUtil.Sleeper.sleep;


@Slf4j(topic = "c.TestTimeout")
public class TestTimeout {
	public static void main(String[] args) {
		test2();

		// test1();

		// test3();
	}

	private static void test3() {
		ReentrantLock lock = new ReentrantLock();
		Thread t1 = new Thread(() -> {
			log.debug("尝试获取锁");
			try {
				if (!lock.tryLock(1, TimeUnit.SECONDS)) {
					log.debug("获取不到锁");
					return;
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
				log.debug("被打断，不再向下执行");
				return;
			}
			log.debug("获得了锁");
			// 释放锁
			lock.unlock();
		});


		lock.lock();
		log.debug("获得了锁");
		try {
			t1.start();
			// 打断等待
			t1.interrupt();
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	private static void test1() {
		ReentrantLock lock = new ReentrantLock();
		Thread t1 = new Thread(() -> {
			log.debug("尝试获取锁");
			try {
				if (!lock.tryLock(3, TimeUnit.SECONDS)) {
					log.debug("获取不到锁");
					return;
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
				log.debug("获取不到锁");
				return;
			}
			try {
				log.debug("获得了锁");
			} finally {
				lock.unlock();
			}
		}, "t1");

		lock.lock();
		log.debug("获得了锁");
		t1.start();
		try {
			sleep(2);
		} finally {
			lock.unlock();
		}
	}

	private static void test2() {
		ReentrantLock lock = new ReentrantLock();
		Thread t1 = new Thread(() -> {
			log.debug("尝试获取锁");
			if (!lock.tryLock()) {
				log.debug("获取不到锁");
				return;
			}
			try {
				log.debug("获得了锁");
			} finally {
				lock.unlock();
			}
		}, "t1");

		lock.lock();
		log.debug("获得了锁");
		t1.start();
		try {
			sleep(2);
		} finally {
			lock.unlock();
		}
	}
}
